package com.yao.smy.utils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件操作工具类
 */
public class FileUtil {

    /**
     * 读取指定路径的txt文件内容
     * @param filePath 文件路径
     * @return 文件内容列表，每行作为一个元素
     * @throws IOException 如果文件读取失败
     */
    public static List<String> readTxtFile(String filePath) throws IOException {
        List<String> lines = new ArrayList<>();
        Path path = Paths.get(filePath);
        if (Files.exists(path)) {
            lines = Files.readAllLines(path, StandardCharsets.UTF_8);
        }
        return lines;
    }

    /**
     * 将内容写入指定路径的txt文件
     * @param filePath 文件路径
     * @param content 要写入的内容
     * @throws IOException 如果文件写入失败
     */
    public static void writeTxtFile(String filePath, String content) throws IOException {
        Path path = Paths.get(filePath);
        Files.write(path, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    }

    /**
     * 将内容追加到指定路径的txt文件
     * @param filePath 文件路径
     * @param content 要追加的内容
     * @throws IOException 如果文件追加失败
     */
    public static void appendToTxtFile(String filePath, String content) throws IOException {
        Path path = Paths.get(filePath);
        Files.write(path, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    }

    /**
     * 扫描指定目录下的所有txt文件
     * @param directoryPath 目录路径
     * @return txt文件路径列表
     * @throws IOException 如果目录扫描失败
     */
    public static List<String> scanTxtFiles(String directoryPath) throws IOException {
        List<String> txtFiles = new ArrayList<>();
        Path dirPath = Paths.get(directoryPath);
        if (Files.isDirectory(dirPath)) {
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(dirPath, "*.txt")) {
                for (Path entry : stream) {
                    txtFiles.add(entry.toString());
                }
            }
        }
        return txtFiles;
    }
}